package cn.com.nes.site.service.workOrder.impl;

import cn.com.nes.common.em.WorkOrderRecordEnum;
import cn.com.nes.common.exception.BusinessException;
import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.util.SMSUtil;
import cn.com.nes.mybatis.agent.ope.entity.IsEquipmentInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsInstallInfo;
import cn.com.nes.mybatis.agent.system.entity.Company;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.mybatis.callcenter.entity.TXzqh;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderRecord;
import cn.com.nes.mybatis.callcenter.mapper.TXzqhMapper;
import cn.com.nes.site.entity.bo.workorder.WorkOrderBO;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.WorkOrderStautsEnum;
import cn.com.nes.site.entity.em.WorkOrderTypeEnum;
import cn.com.nes.site.service.monitor.EquipmentService;
import cn.com.nes.site.service.monitor.IsInstallInfoService;
import cn.com.nes.site.service.system.company.BusinessCompanyService;
import cn.com.nes.site.service.system.user.CcUserService;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.com.nes.site.service.workOrder.WorkOrderRecordService;
import cn.com.nes.site.service.workOrder.WorkOrderService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 经销商
 */
@Service
public class RepairWorkOrderBuilder extends WorkOrderBuilder {
    @Resource
    private SystemUserService systemUserService;
    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private WorkOrderRecordService workOrderRecordService;

    @Resource

    private IsInstallInfoService isInstallInfoService;

    @Resource
    private CcUserService ccUserService;

    @Resource
    private BusinessCompanyService businessCompanyService;
    @Resource

    private TXzqhMapper tXzqhMapper;
    /**
     * 阿里云sms key
     */
    private static String aliyunAppkey="LTAI4FonwN8mFFcgS5Nssy22";
    /**
     * 阿里云 sms 密钥
     */

    private static String aliyunSecret="vowstPO9mUkkCdDhRUHvKSItqJLIrw";

    /**
     * 维修通知
     */
    private final String maintainSignname = "维修通知";
    /**
     * 客户
     */
    private String userTemplate="SMS_155861802";

    /**
     * 您的工单已派单，维修师傅${name}，电话${phone]，维修签到验证码${code}请您保持电话畅通!
     */
    private String userTemplate2="SMS_474525143";

    /**
     * 客户
     */
    private String appointmentUserTemplate="SMS_261190260";

    /**
     * 您的工单已分配，维修师傅 ${name}，电话${phone]，师傅将按时上门维修!维修签到验证码${code}
     */
    private String appointmentUserTemplate2="SMS_464095968";

    /**
     * 维修人员
     */
    private String staffTemplate="SMS_474435200";


    @Override
    public String getType() {
        return WorkOrderTypeEnum._1.getKey();
    }

    @Override
    protected void saveEquipmentInfo(WorkOrderBO workOrderbo) throws Exception {
        IsEquipmentInfo isEquipmentInfo =null;
        if (workOrderbo.getEquipmentIds()==null) {
            isEquipmentInfo = new IsEquipmentInfo();
            isEquipmentInfo.setManufactureId(workOrderbo.getOperateUserCompanyId());
            isEquipmentInfo.setSblxId("");
            isEquipmentInfo.setScddh("");
            isEquipmentInfo.setBdzt(0);
            isEquipmentInfo.setBz("创建维修工单生成设备");
            isEquipmentInfo.setSfsc(0);
            isEquipmentInfo.setCjsj(workOrderbo.getOperateDate());
            isEquipmentInfo.setXgsj(workOrderbo.getOperateDate());
            isEquipmentInfo.setUpOper(String.valueOf(workOrderbo.getOperateUserId()));
            isEquipmentInfo.setCreateOper(String.valueOf(workOrderbo.getOperateUserId()));
            isEquipmentInfo.setDdId(workOrderbo.getHouseUUid());
            isEquipmentInfo.setJd(workOrderbo.getLongitude());
            isEquipmentInfo.setWd(workOrderbo.getLatitude());
            Integer rows = equipmentService.saveEquipmentInfo(isEquipmentInfo);
            if (rows <= 0) {
                throw new BusinessException("保存设备信息失败！");
            }
            workOrderbo.setEquipmentIds(isEquipmentInfo.getSbId());
            saveInstallInfo(workOrderbo);
        }
    }

    protected void saveInstallInfo(WorkOrderBO workOrderBO) throws Exception {
        TUser installUserInfo = systemUserService.getUserInfoByUserId(workOrderBO.getMaintainId().toString());
        if (ObjectUtil.isNull(installUserInfo) || ObjectUtil.isNull(installUserInfo.getCallCenterUserId())) {
            throw new IllegalBusinessException("转换维修id异常,维修人信息:" + JSON.toJSONString(installUserInfo));
        }
        IsInstallInfo isInstallInfo= new IsInstallInfo();
        isInstallInfo.setManufactureId(workOrderBO.getOperateUserCompanyId());
        isInstallInfo.setKhId(workOrderBO.getClienteleId());
        isInstallInfo.setDdId(workOrderBO.getHouseUUid());  // 2024-06 项目组决定将地点id定义为房屋业务id
        isInstallInfo.setAzsgrq(workOrderBO.getOperateDate());
        isInstallInfo.setAzwcrq(workOrderBO.getOperateDate());
        isInstallInfo.setLxdh(workOrderBO.getPhone());
        isInstallInfo.setXmlxr(workOrderBO.getCustomerName());
        isInstallInfo.setXmlxrdh(workOrderBO.getPhone());
        isInstallInfo.setXmdz(workOrderBO.getAddress());
        isInstallInfo.setXzqh(workOrderBO.getXzqhdm());
        isInstallInfo.setMph(workOrderBO.getHouseNumber());
        isInstallInfo.setJd(workOrderBO.getLongitude());
        isInstallInfo.setWd(workOrderBO.getLatitude());
        isInstallInfo.setType(2);           // 先默认为户用
        isInstallInfo.setSjly("agent");     // 默认 agent
        isInstallInfo.setAuditState("1");   // 默认审核通过
        isInstallInfo.setBelongTo(workOrderBO.getUserInfo().getNes_companyId());
        isInstallInfo.setXzqh(workOrderBO.getXzqhdm());
        isInstallInfo.setSfsc(0);
        isInstallInfo.setXgsj(workOrderBO.getOperateDate());
        isInstallInfo.setTsr(installUserInfo.getNickName());
        isInstallInfo.setTsrdh(installUserInfo.getPhone());
        isInstallInfo.setYzxm(workOrderBO.getCustomerName());
        isInstallInfo.setZbrq(workOrderBO.getOperateDate());
        isInstallInfo.setZbq(0L);
        isInstallInfoService.saveOrUpdate(isInstallInfo);
    }

    @Override
    protected void validDefaultField(WorkOrderBO workOrderBO) {
       if(ObjectUtil.isEmpty(workOrderBO.getEmergencyDegreeId())){
           throw new BusinessException("紧急程度不能为空");
        }
        if (ObjectUtil.isEmpty(workOrderBO.getWorkTypeId())){
            throw new BusinessException("工单任务类型不能为空");
        }
        if(StringUtils.isEmpty(workOrderBO.getAppealCategory())){
            throw new BusinessException("问题分类不能为空");
        }
        if(StringUtils.isEmpty(workOrderBO.getDesc())){
            throw new BusinessException("描述不能为空");
        }
        if(ObjectUtil.isEmpty(workOrderBO.getMaintainId()) && StringUtils.isEmpty(workOrderBO.getCompanyId())){
            throw new BusinessException("业务支持人员或公司不能为空");
        }
    }

    @Override
    public String createWorkOrder(WorkOrderBO workOrderBO) throws Exception {
        Long workOrderId = workOrderService.createRepairWorkOrder(workOrderBO);
        return workOrderId.toString();
    }

    @Override
    protected void saveWorkOrderRecord(WorkOrderBO workOrderBO, String workOrderId) throws Exception {
        Company company = businessCompanyService.getCompany(workOrderBO.getCompanyId());
        WorkOrderRecord record = new WorkOrderRecord();
        record.setGmtCreate(workOrderBO.getOperateTimeStamp());
        record.setGmtModified(workOrderBO.getOperateTimeStamp());
        record.setIsDelete(DeleteEnum._0.getKey());
        record.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
        record.setDesc(company.getCompanyname()+"的客服中心创建了工单");
        record.setWorkOrderId(Long.parseLong(workOrderId));
        record.setUserId(workOrderBO.getUserInfo().getCallCenterUserId());//转换为长效管护的id
        TUser installUserInfo = systemUserService.getUserInfoByUserId(workOrderBO.getMaintainId());
        if(workOrderBO.getCompanyId().equals(workOrderBO.getOperateUserCompanyId())) {
            record.setMaintainId(installUserInfo.getCallCenterUserId()); //转换为长效管护的id
            if (ObjectUtil.isNull(installUserInfo) || ObjectUtil.isNull(installUserInfo.getCallCenterUserId())) {
                throw new IllegalBusinessException("转换安装人id异常,安装人信息:" + JSON.toJSONString(installUserInfo));
            }
        }else{

            WorkOrderRecord record1 = new WorkOrderRecord();
            record1.setGmtCreate(workOrderBO.getOperateTimeStamp());
            record1.setGmtModified(workOrderBO.getOperateTimeStamp());
            record1.setIsDelete(DeleteEnum._0.getKey());
            record1.setStatus(Integer.parseInt(WorkOrderStautsEnum._2.getKey()));
            Company currentCompany = businessCompanyService.getCompany(workOrderBO.getOperateUserCompanyId());
            record1.setDesc(currentCompany.getCompanyname()+"的客服中心的"+workOrderBO.getOperateUserName()+"向"+company.getCompanyname()+"的客服中心的"+installUserInfo.getNickName()+"(处理人)转派了工单");
            record1.setWorkOrderId(workOrderBO.getPWorkOrderId());
            record1.setUserId(workOrderBO.getUserInfo().getCallCenterUserId());
            record1.setMaintainId(installUserInfo.getCallCenterUserId());
            workOrderRecordService.saveWorkOrderRecord(record1);
        }
        workOrderRecordService.saveWorkOrderRecord(record);
    }

    @Override
    protected void sendAliSms(WorkOrderBO workOrderBO) {
        if(ObjectUtil.isNotEmpty(workOrderBO.getMaintainId())) {
            TUser installUserInfo = systemUserService.getUserInfoByUserId(workOrderBO.getMaintainId().toString());
            //给客户发送维修人员的信息
            JSONObject params = new JSONObject();
            params.put("name", installUserInfo.getNickName());
            params.put("phone", installUserInfo.getPhone());
            params.put("phone", "13716172770");
            params.put("code", workOrderBO.getVerificationCode());
            // 立即上门
            SMSUtil.sendAliSmsCallCenter(aliyunAppkey, aliyunSecret, maintainSignname, userTemplate2, "13716172770", params);/*workOrderBO.getPhone()*/
            //给维修人员发维修并发送客户信息
            String name = workOrderBO.getCustomerName() + workOrderBO.getPhone();
            name = concatAreaName(name, workOrderBO.getXzqhdm());
            SMSUtil.sendMaintainSms(aliyunAppkey, aliyunSecret, maintainSignname, staffTemplate, "13716172770",
                    name);/*installUserInfo.getPhone()*/
        }
    }
    private String concatAreaName(String name,String xzqhdm) {
        TXzqh tXzqh = tXzqhMapper.getAreaInfo(xzqhdm);
        if (ObjectUtil.isNotNull(tXzqh)) {
            String xzqhmc = tXzqh.getXzqhmc();
            if (StrUtil.isNotBlank(xzqhmc)) {
                name = xzqhmc + "_" + name;
            }
        }
        return name;
    }
}
